package com.imu.utils;

import org.apache.commons.io.FileUtils;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


/*****
 * 工具类
 * @author sunhongwei
 * @email sunhongwei@gmail.com
 * @date 2017年11月4日 上午11:07:35
 */
public class Util
{
	public static String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SZ";
	public static String SIMPLE_DATE_FORMAT = "yyyy-MM-dd";

	private static final String EMAIL_PATTERN = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@"
											  + "[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";

	public static boolean validateEmail(final String hex)
	{
		Pattern pattern = Pattern.compile(EMAIL_PATTERN);
		Matcher matcher = pattern.matcher(hex);
		return matcher.matches();
	}

	
	public static void createZipFile(String path,File...files)
	{
		ZipOutputStream zip = null;
		FileOutputStream dest = null;
		try{
			File f = new File(path);
			dest = new FileOutputStream(f);
			zip = new ZipOutputStream(new BufferedOutputStream(dest));
			for (File file : files) {
				zip.putNextEntry(new ZipEntry(file.getName()));
				zip.write(FileUtils.readFileToByteArray(file));
				zip.closeEntry();
			}
		}catch(Exception e){
			e.printStackTrace();
			throw new RuntimeException("Unable to create zip file");
		}finally{
			try{
				if(zip!=null)
					zip.close();
				if(dest!=null)
					dest.close();

			}catch(Exception ioe){
				//Nothing to do
			}
		}
	}


	public static String encode(String code)
	{
		/*
		if(StringUtils.isNumeric(code)){
			String content = NumberUtils.createBigInteger(code).toString(8);
			BigInteger value = NumberUtils.createBigInteger(content);
			return String.valueOf(value.add(value));
		}*/
		
		return code;
	}

	public static String decode(String code)
	{
		/*
		if(StringUtils.isNumeric(code)){
            String value = NumberUtils.createBigInteger(code).divide(new BigInteger("2")).toString();
            BigInteger orignal = new BigInteger(value,8);
            return orignal.toString();
		}*/
		
		return code;
	}

	public static String getDate(Date date) 
	{
		SimpleDateFormat formatter = new SimpleDateFormat(DATE_FORMAT);
		return formatter.format(date);
	}

	public static String getSimpleDate(Date date)
	{
		SimpleDateFormat formatter = new SimpleDateFormat(SIMPLE_DATE_FORMAT);
		return formatter.format(date);
	}

	public static String getRandNum(int charCount) 
	{
		String charValue = "";
		
		for (int i = 0; i < charCount; i++) 
		{
			char c = (char) (randomInt(0, 10) + '0');
			charValue += String.valueOf(c);
		}
		
		return charValue;
	}
	
	public static int randomInt(int from, int to)
	{
		Random r = new Random();
		return from + r.nextInt(to - from);
	}

	/**
	 * 传入文本内容，返回 SHA-256 串
	 *
	 * @param strText
	 * @return
	 */
	public static String SHA256(final String strText)
	{
		return SHA(strText, "SHA-256");
	}

	/**
	 * 传入文本内容，返回 SHA-512 串
	 *
	 * @param strText
	 * @return
	 */
	public static String  SHA512(final String strText)
	{
		return SHA(strText, "SHA-512");
	}

	/**
	 * 字符串 SHA 加密
	 *
	 * @param strText
	 * @return
	 */
	private static String SHA(final String strText, final String strType)
	{
		// 返回值
		String strResult = null;

		// 是否是有效字符串
		if (strText != null && strText.length() > 0)
		{
			try
			{
				// SHA 加密开始
				// 创建加密对象 并傳入加密類型
				MessageDigest messageDigest = MessageDigest.getInstance(strType);
				// 传入要加密的字符串
				messageDigest.update(strText.getBytes());
				// 得到 byte 類型结果
				byte byteBuffer[] = messageDigest.digest();

				// 將 byte 轉換爲 string
				StringBuffer strHexString = new StringBuffer();
				// 遍歷 byte buffer
				for (int i = 0; i < byteBuffer.length; i++)
				{
					String hex = Integer.toHexString(0xff & byteBuffer[i]);
					if (hex.length() == 1)
					{
						strHexString.append('0');
					}
					strHexString.append(hex);
				}
				// 得到返回結果
				strResult = strHexString.toString();
			}
			catch (NoSuchAlgorithmException e)
			{
				e.printStackTrace();
			}
		}

		return strResult;
	}

	public static double parseMoney(double fee)
	{
		BigDecimal b = new BigDecimal(fee);
		return b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}

	public static double parseMoney(String fee)
	{
		BigDecimal b = new BigDecimal(fee);
		return b.setScale(2,BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	/**
     * 判断是否是连号 
     * @param str 字符 
     * @return
     */
    public static final boolean getCharEq(String str)
    {
        int num = 0;
        char[] chars = str.toCharArray();
        char c = chars[0];
        int len = chars.length;
        
        for(int i = 0; i < len; i++)
        {
            if(c == chars[i])
            {
                num++;
            }
        }

        if(num == len) return true;
        
        return false;
    }
}
